import AI from '../modules/AI.js';

/** 生成uuid */
export function generateUUID() {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
        var r = (Math.random() * 16) | 0,
            v = c == 'x' ? r : (r & 0x3) | 0x8;
        return v.toString(16);
    });
}

/** 获取随机范围内的整数 */
export function getRandomInt(min, max) {
    min = Math.ceil(min);
    max = Math.floor(max);
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

/** 判断两个圆是否相碰撞 true表示相撞 */
export function isCircleColliding(circle1, circle2) {
    const { radius: r1 } = circle1;
    const { radius: r2 } = circle2;
    // 计算两个圆心之间的距离
    const distance = getDistanceBetweenCircles(circle1, circle2);

    // 判断是否发生碰撞
    return distance <= r1 + r2;
}

/** 计算两个圆心之间的距离 */
export function getDistanceBetweenCircles(circle1, circle2) {
    // 获取两个圆的坐标和半径
    const { x: cx1, y: cy1, radius: r1 } = circle1;
    const { x: cx2, y: cy2, radius: r2 } = circle2;

    // 计算两个圆心之间的距离
    return Math.sqrt((cx2 - cx1) ** 2 + (cy2 - cy1) ** 2);
}

/** 判断两个矩形相碰撞 */
export function isRectangleColliding(rect1, rect2) {
    // 获取矩形的坐标和尺寸
    const { x: x1, y: y1, width: w1, height: h1 } = rect1;
    const { x: x2, y: y2, width: w2, height: h2 } = rect2;

    // 判断矩形是否相交
    if (x1 < x2 + w2 && x1 + w1 > x2 && y1 < y2 + h2 && y1 + h1 > y2) {
        return true;
    } else {
        return false;
    }
}

/** 寻找到数字数组中最大值所在数组的下标 */
export function findMaxIndex(arr) {
    let maxIndex = 0;
    for (let i = 1; i < arr.length; i++) {
        if (arr[i] > arr[maxIndex]) {
            maxIndex = i;
        }
    }
    return maxIndex;
}

/** 生成高斯分布（正态分布）的随机数，生成一个-1到1之间的随机数 */
export function randomGaussian() {
    return Math.random() * 2 - 1;
}

export function pickOne(savedPlayerArr, ctx) {
    let index = 0;
    let r = Math.random();
    while (r > 0) {
        r = r - savedPlayerArr[index].fitness;
        index++;
    }
    index--;
    let bestPlayer = savedPlayerArr[index];
    let newPlayer = new AI(
        ctx,
        getRandomInt(50, window.GameData.canvas.width - 50),
        getRandomInt(50, window.GameData.canvas.height - 50),
        bestPlayer.brain
    );
    newPlayer.mutate();
    return newPlayer;
}

export function calculateFitness(savedPlayerArr) {
    let sum = 0;
    for (let savedPlayer of savedPlayerArr) {
        sum += savedPlayer.score;
    }
    for (let savedPlayer of savedPlayerArr) {
        savedPlayer.fitness = savedPlayer.score / sum;
    }
}
